package com.sunmoon.mingshuo.spider


import com.blankj.utilcode.util.TimeUtils.string2Millis
import com.sunmoon.mingshuo.data.Chapter
import com.sunmoon.mingshuo.data.Search
import com.sunmoon.mingshuo.data.SearchItem
import org.jsoup.Jsoup
import java.text.SimpleDateFormat
import java.util.*

class SouduSpider {
    val baseUrl = "http://www.sodu.cc/result.html?searchstr="
    private val mFormat = SimpleDateFormat("yyyy/M/d HH:mm:ss", Locale.getDefault())
    fun search(keyword:String):Search{
        var doc = Jsoup.connect("$baseUrl$keyword").get()
        var searchContent = doc.select("div.main-html")
        var search = Search(keyword, "$baseUrl$keyword", mutableListOf())
        for (item in searchContent) {
            var div1 = item.select("div:first-child")
            var div1a = div1.select("a:first-child")
            var title = div1a.html()
            var url = div1a.attr("href")
            var subTitle = item.select("div:nth-child(2) a").html()
            var time = item.select("div:nth-child(3)").html()
            search.res.add(SearchItem(title,url,subTitle, string2Millis(time, mFormat)))
        }
        return search
    }
    fun getChapters(url:String):MutableList<Chapter>{
        var doc  = Jsoup.connect(url).get()
        var elements = doc.select("div.main-html")
        var chapters =  mutableListOf<Chapter>()
        for (element in elements) {
            var div1 = element.select("div:first-child")
            var div1a = div1.select("a:first-child")
            var title = div1a.html()
            var url = div1a.attr("href")
            var src = element.select("div:nth-child(2) a").html()
            var time = element.select("div:nth-child(3)").html()
            chapters.add(Chapter(title,url,src, string2Millis(time, mFormat)))
        }
        return chapters
    }
}